import tkinter as tk
from tkinter import scrolledtext
import random
import json

# 初始化数据
data = []
size = 200


def set_data():
    global data
    data = []
    for i in range(size):
        rand = random.randint(0, 1000)
        data.append(rand)
    # 逐行显示数组
    show(data)


def one():
    global data
    # 升序排序
    data.sort()
    # 去掉极大值和极小值
    l = int(len(data) * 0.1)
    data = data[l:-l]
    # 最大值 - 最小值
    max_min = data[-1] - data[0]
    result_text = ""
    for i in range(len(data)):
        num = (data[i] - data[0]) / max_min
        num = int(num * 100)
        result_text += f"{i + 1}的最终得分为：{num}分\n"
    result_label.config(text=result_text)
    show(data)


def add():
    global data
    try:
        num = float(new_data_entry.get())
        data.append(num)
        show(data)
    except ValueError:
        pass


def show(arr):
    text_area.delete(1.0, tk.END)
    text_area.insert(tk.END, json.dumps(arr).replace(',', ',\n'))


def update():
    global data
    try:
        data = json.loads(text_area.get(1.0, tk.END))
    except json.JSONDecodeError:
        pass


# 创建主窗口
root = tk.Tk()
root.title("归一算法（综合竞争力排名）")

# 创建组件
final_score_label = tk.Label(root, text="最终得分")
final_score_label.pack()

text_area = scrolledtext.ScrolledText(root, width=40, height=10)
text_area.pack()

tf = tk.Frame(root)
tf.pack()
random_data_button = tk.Button(tf, text="随机生成数据", command=set_data)
random_data_button.pack(side=tk.LEFT)

new_data_label = tk.Label(tf, text="新数据:")
new_data_label.pack(side=tk.LEFT)

new_data_entry = tk.Entry(tf)
new_data_entry.pack(side=tk.LEFT)

add_data_button = tk.Button(tf, text="添加新数据", command=add)
add_data_button.pack(side=tk.LEFT)

update_button = tk.Button(tf, text="更新数据", command=update)
update_button.pack(side=tk.LEFT)

calculate_button = tk.Button(tf, text="计算得分", command=one)
calculate_button.pack(side=tk.LEFT)


fg = tk.Frame(root)
fg.pack()
result_label = tk.Label(fg, text="")
result_label.pack(fill=tk.BOTH)

# 初始化数据
set_data()

# 运行主循环
root.mainloop()